package org.example;

/**
 * @author zwt
 * @version 1.0
 * @data 2024/12/20 23:36
 */

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private UserDAO userDAO = new UserDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/login.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String role = request.getParameter("role");

        User user = null;

        if ("admin".equals(role)) {
            user = userDAO.adminLogin(username, password);
            if (user != null) {
                HttpSession session = request.getSession();
                session.setAttribute("admin", user);
                response.sendRedirect(request.getContextPath() + "/admin");
                return;
            } else {
                request.setAttribute("error", "无效的管理员用户名或密码");
            }
        } else {
            user = userDAO.login(username, password);
        }

        if (user != null) {
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            response.sendRedirect(request.getContextPath() + "/home.jsp");
        } else {
            request.setAttribute("error", "无效的用户名或密码");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }
}
